/* Based on the sourcecode of APN-Switch (C) 2011 Adrian Ulrich */

package org.nfx.defyplus.datatoggle;

import java.lang.reflect.Method;

import android.content.Context;
import android.net.ConnectivityManager;

public class MobileData {
    /**
     * Checks if mobile data is enabled.
     *
     * @param context a reference to Context or Activity
     * @return true if data enabled.
     */
	private static void log(String lmsg) {
		android.util.Log.d("BlurDataToggle INFO: ", lmsg);
	}
    public static boolean   isEnable(Context context) {
		boolean result = false;
		try {
			ConnectivityManager cmgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
			Method method = cmgr.getClass().getMethod("getMobileDataEnabled");
			method.setAccessible(true);
			result = (Boolean)method.invoke(cmgr);
		}
		catch(Exception e) {
			log("Error: "+e);
		}
		log("API returns: "+result);
		return result;
    }

    /**
     * Turn off mobile data.
     *
     * @param context a reference to Context or Activity
     */
    public static void disable(Context context) {
        switchState(context, false);
    }

    /**
     * Turn on mobile data.
     *
     * @param context a reference to Context or Activity
     */
    public static void enable(Context context) {
        switchState(context, true);
    }   

    private static void switchState(Context context, boolean isOn) {
		try {
			ConnectivityManager cmgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
			Method method = cmgr.getClass().getMethod("setMobileDataEnabled", boolean.class);
			method.invoke(cmgr, isOn);
			
			for(int retry = 0; retry < 10; retry++) {
				Thread.sleep(100);
				if( isEnable(context) == isOn ) {
					log("BREAKOUT at "+retry);
					break;
				}
			}
			
		}
		catch(Exception e) {
			log("Error: "+e);
		}
    }
}
